package client.lobby;

import java.io.ObjectInputStream;
import java.io.PrintWriter;

import shared.player.Player;
import shared.util.Config;
import client.game.GameWindow;
import client.gui.ErrorMessageGui;
import client.gui.LobbyGui;

/**
 * The Class WaitingLobby
 * - contains information about the player, his opponents
 * and also opens a game window.	
 */
public class WaitingLobby extends Thread {

	/** Traffic in. */
	ObjectInputStream netIn;
	
	/** Traffic out. */
	PrintWriter netOut;
	
	/** The players in the game. */
	Player p, opp1, opp2;
	
	/** The player name. */
	String name;
	
	/** The lobby gui. */
	LobbyGui lobbyGui;
	
	/** If true, opens the gameWindow. */
	boolean start = false;
	
	/** The configuration object. */
	Config conf;

	/**
	 * Instantiates a new waiting lobby.
	 *
	 * @param name the name of the player
	 * @param netIn the inbound traffic
	 * @param netOut the outbound traffic
	 * @param conf the configuration object
	 */
	public WaitingLobby(String name, ObjectInputStream netIn, PrintWriter netOut, Config conf) {
		this.name = name;
		this.netIn = netIn;
		this.netOut = netOut;
		this.conf = conf;
		lobbyGui = new LobbyGui(name);
		@SuppressWarnings("unused")
		StartListener startListener = new StartListener(netIn, this, name);
		start();
	}

	/**
	 * Sets the start value to true.
	 *
	 */
	public void setGame() {
		start = true;
	}

	/**
	 * Sets the player object of this lobby.
	 *
	 * @param p the new player
	 */
	public void setPlayer(Player p) {
		this.p = p;
	}

	/**
	 * Sets the first opponent.
	 *
	 * @param p the new opponent
	 */
	public void setOpp1(Player p) {
		opp1 = p;
	}
	
	/**
	 * Sets the second opponent
	 *
	 * @param p the new opponent
	 */
	public void setOpp2(Player p) {
		opp2 = p;
	}

	/**waits for the game start, disposes of the lobby gui, open a new game window
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		while (true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				new ErrorMessageGui("Sleep interrupted");
			}
			if (start) {
				lobbyGui.dispose();
				new GameWindow(p, opp1, opp2, netIn, netOut, conf);
				break;
			}else{
				continue;
			}
		}
	}
}